﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TasksUI
{
    public partial class FindTask : Form
    {
        public FindTask()
        {
            InitializeComponent();
        }

        public FindTask(TasksModel.TaskLibrary library)
            : this()
        {
            this.library = library;
        }

        public static void Show(TasksModel.TaskLibrary library)
        {
            using (FindTask f = new FindTask(library))
            {
                f.ShowDialog(Form.ActiveForm);
            }
        }

        private TasksModel.TaskLibrary library;

        private void bClose_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void FindTask_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                bSearch_Click(null, null);
            else
                if (e.KeyChar == (char)27)
                    bClose_Click(null, null);
        }

        private void bSearch_Click(object sender, EventArgs e)
        {
            TasksModel.TaskSearchCriteria cr = new TasksModel.TaskSearchCriteria();

            string[] tags = tbTags.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tag in tags)
                cr.Tags.Add(tag.Trim());

            cr.Name = tbName.Text.Trim();
            cr.Flag = tbFlag.Text.Trim();
            cr.Status = tbStatus.Text.Trim();
            cr.Content = tbContent.Text.Trim();
            cr.Author = tbAuthor.Text.Trim();
            if (dtpDueFrom.Checked)
                cr.DueAtFrom = dtpDueFrom.Value;
            if (dtpDueTo.Checked)
                cr.DueAtTo = dtpDueTo.Value;
            if (dtpCreatedFrom.Checked)
                cr.CreatedAtFrom = dtpCreatedFrom.Value;
            if (dtpCreatedTo.Checked)
                cr.CreatedAtTo = dtpCreatedTo.Value;
            if (dtpChangedFrom.Checked)
                cr.ChangedAtFrom = dtpChangedFrom.Value;
            if (dtpChangedTo.Checked)
                cr.ChangedAtTo = dtpChangedTo.Value;
            //todo?
            //cr.Priorities
            //cr.Classes

            TasksModel.TaskObservableCollection<TasksModel.Task> tl = cr.Select(library, false);
            if (tl.Count == 0)
            {
                MessageBox.Show(this, "No tasks found.", "Find");
                return;
            }
            Form sr = new SearchResults(tl.ToList());
            sr.ShowDialog(Owner);
            Focus();
        }
    }
}